package com.happymmall.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.happymmall.entity.User;
import com.happymmall.service.UserService;
import com.happymmall.service.impl.UserServiceImpl;
import com.happymmall.util.Constants;
import com.happymmall.util.JwtUtils;
import com.happymmall.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/user/login.do")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        // 修改密码参数处理
        String password = MD5Util.md5Encode(req.getParameter("password"));

        User user = userService.login(username, password);

        if (user != null) {
            // 将用户的信息放到Session中
            //  HttpSession session = req.getSession();
            //req.getSession().setAttribute(Constants.USER_SESSION, user.getId());
            Map<String, Object> claims = new HashMap<>();
            claims.put(Constants.USER_TOKEN, user.getId());
            String token = JwtUtils.generateToken(claims);
            // 处理中文乱码
            resp.setContentType("application/json;charset=utf-8");
            System.out.println("用户登录成功");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 0);
            resultData.put("data", user);
            resultData.put("token", token);

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);

        } else {
            resp.setContentType("application/json;charset=utf-8");
            Map<String, Object> resultData = new HashMap();
            resultData.put("status", 1);
            resultData.put("msg", "用户名或密码不正确！");

            JSONObject jsonObject = new JSONObject();
            String info = jsonObject.toJSONString(resultData);
            PrintWriter out = resp.getWriter();
            out.write(info);
        }

    }


}
